package com.imau.brand.common.handler;

import com.alibaba.fastjson.JSON;
import com.imau.brand.common.entity.ResultCode;
import com.imau.brand.common.entity.ResultEntity;
import com.imau.brand.common.exception.CommonException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/BaseExceptionHandler")
public class BaseExceptionHandler extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设置统一编码
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");
        //web.xml中配置异常错误拦截处理
        // Analyze the servlet exception - www.yiibai.com
        //http://www.yiibai.com/doc/jsp/servlet_exception_handling.html
        Throwable throwable = (Throwable)
                request.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer)
                request.getAttribute("javax.servlet.error.status_code");
        String servletName = (String)
                request.getAttribute("javax.servlet.error.servlet_name");
        System.out.println("statusCode" + statusCode);
        System.out.println("servletName" + servletName);

        //统一响应异常结果
        ResultEntity error = this.errorHandeler(request, response, throwable);
        String strJson = JSON.toJSONString(error);
        response.getWriter().write(strJson);
    }

    public ResultEntity errorHandeler(HttpServletRequest request,
                                      HttpServletResponse response, Throwable e) {
        if (e.getClass() == CommonException.class) {
            //类型转型
            CommonException ce = (CommonException) e;
            ResultEntity result = new ResultEntity(ce.getResultCode());
            return result;
        } else {
            ResultEntity result = new ResultEntity(ResultCode.SERVER_ERROR);
            return result;
        }
    }
}
